import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class Demo6MapReduceWriteHBase {
    // 读取HDFS的students.txt文件，统计每个班级人数，结果写回HBase，写入clazz_num
    public static class MyMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] splits = value.toString().split(",");
            String clazz = splits[4];
            context.write(new Text(clazz), new IntWritable(1));
        }
    }

    public static class WriteHBaseReducer extends TableReducer<Text, IntWritable, NullWritable> {
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable i : values) {
                sum += i.get();
            }
            // create 'clazz_num','cf1'
            Put put = new Put(key.toString().getBytes());
            put.addColumn("cf1".getBytes(), "num".getBytes(), Bytes.toBytes(sum));

            context.write(NullWritable.get(), put);

        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "master,node1,node2:2181");

        Job job = Job.getInstance(conf);
        job.setJobName(Demo6MapReduceWriteHBase.class.getName());
        job.setJarByClass(Demo6MapReduceWriteHBase.class);

        // 配置map任务
        job.setMapperClass(MyMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        // 输入路径
        FileInputFormat.addInputPath(job, new Path("/input3"));

        // 配置reduce任务
        // 使用HBase提供的TableMapReduceUtil工具进行配置
        TableMapReduceUtil.initTableReducerJob("clazz_num", WriteHBaseReducer.class, job);

        job.waitForCompletion(true);
        /*
        hadoop jar HBaseJavaAPI11-1.0-jar-with-dependencies.jar  Demo6MapReduceWriteHBase
         */
    }
}
